import * as filterConfigs from "../../../models/filterConfigs"
import * as transferData from "../../../models/transferData";
import p from "../../../utils/platform";
import {cooperationBehavior} from "../../../behaviors/cooperation.js";
import {getActiveStr} from '../../../utils/utilsNew';
import util from "../../../utils/util.js";
import api from "../../../common/api";

const computedBehavior = require("miniprogram-computed");
const app = getApp();
Page({
  behaviors: [cooperationBehavior, computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    id: '', //编辑接口需要的id
    valueLength: '0', //房源备注说明--已经输入的字数
    endTime: '', //挂牌时间的截至时间
    cooperationId: '', //合作房源的房子Id ---用来在编辑页面查询使用
    moreOptions: [{
      id: 'serviceLife',
      title: '年限',
      red: '*',
      select: 'single',
      options: filterConfigs.serviceLife
    }, {
      id: 'notTheOnly',
      title: '是否唯一',
      red: '*',
      select: 'single',
      options: filterConfigs.notTheOnly
    }, {
      id: 'floor',
      title: '楼层',
      red: '*',
      select: 'single',
      options: filterConfigs.floor
    }, {
      id: 'decoration',
      title: '装修',
      red: '*',
      select: 'single',
      options: filterConfigs.decoration
    }, {
      id: 'orientation',
      title: '朝向',
      red: '*',
      select: 'single',
      options: filterConfigs.orientation
    }, {
      id: 'feature',
      title: '房源亮点',
      select: 'multi',
      options: filterConfigs.lightSpotType
    }],
    houseTypeOptions: [{
      id: 'room',
      title: '卧室数量',
      input: {
        unit: '室'
      },
      single: filterConfigs.room,
    }, {
      id: 'hall',
      title: '客厅餐厅数量',
      input: {
        unit: '厅'
      },
      single: filterConfigs.hall
    }, {
      id: 'toilet',
      title: '卫生间数量',
      input: {
        unit: '卫'
      },
      single: filterConfigs.toilet
    }],
    moreValue: {
      feature: [],
      serviceLife: '',
      floor: '',
      decoration: '',
      orientation: '',
      notTheOnly: '',
    },
    backFromInputTextValuePageCb: null, //从页面回来的回调
    houseTitle: '', //房源标题
    delegationType: '', //房源类型  出租还是二手
    model: {
      room: '', //室
      hall: '', //厅
      toilet: '', //卫
    },
    buildSize: '', //面积
    totalPrices: '', //售价/租金
    hdResblockId: '', //小区id---用于数据检测
    isShowHouseTypeSheet: false, //控制户型组件是否显示
    chlikData: '', //挂牌时间
    imgArray: [], //图片数组
    imgMin: 3, //最小图片数
    imgMax: 10, //最大图片数
    isSaving: false, //图片保存中
    inputFloorNum: '', //楼层位于
    buyPrice: '', //买进价
    textInfo: '', //房源备足说明
    isShowDataDetection: false, //用来控制数据监测弹窗的显示
    dataDetectionInfo: '', //检测弹窗需要的数据

    // 暂存三个字段
    totalPricesSave: '',
    buildSizeSave: '',
    delId: '',
    authenticityId: ''
  },
  computed: {
    // 用来判断提交按钮是否高亮
    isPublishAble(data) {
      const {
        moreValue,
        delegationType,
        houseTitle,
        model,
        buildSize,
        totalPrices
      } = data || {}
      return (
        model.room &&
        model.hall &&
        model.toilet &&
        buildSize && buildSize !== '0' &&
        totalPrices && totalPrices !== '0' &&
        data.imgArray.length >= data.imgMin &&
        (delegationType === 'SALES' ? moreValue.serviceLife &&
          houseTitle !== '' &&
          moreValue.floor &&
          moreValue.decoration &&
          moreValue.notTheOnly &&
          moreValue.orientation : true)
      );
    },
    $houseTitle(data) {
      return getActiveStr(data.houseTitle, 30)
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.loginPromise.then(() => {
      // picker组件 限制末端时间
      let nweTime = new Date().getTime()
      nweTime = util.dateFormat(new Date(nweTime), "yyyy-MM-dd")
      this.setData({
        endTime: nweTime,
        cooperationId: options.cooperationId,
      });
      this.getHouseInfo();
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.backFromInputTextValuePageCb) {
      this.data.backFromInputTextValuePageCb()
      this.data.backFromInputTextValuePageCb = null
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 此处调用房源详情的接口来查询编辑的数据
  getHouseInfo() {
    const that = this
    wx.showLoading({
      title: '加载中...',
    })
    that.getInfoByCooperationId(that.data.cooperationId, true).then((res) => {
      // 给编辑的form赋值
      let editData = res.hmCooperationDelVO
      that.setData({
        id: res.houseCooperation.id,
        hdResblockId: editData.hdResblockId,
        houseTitle: editData.title,
        totalPrices: editData.delegationType == 'SALES' ? (editData.totalPrices / 10000) : editData.totalPrices,
        totalPricesSave: editData.delegationType == 'SALES' ? (editData.totalPrices / 10000) : editData.totalPrices,
        delegationType: editData.delegationType,
        'model.room': editData.room > 3 ? { input: editData.room } : String(editData.room),
        'model.hall': editData.hall > 2 ? { input: editData.hall} : String(editData.hall),
        'model.toilet': editData.toilet > 2 ? { input: editData.toilet } : String(editData.toilet),
        buildSize: editData.buildSize,
        buildSizeSave: editData.buildSize,
        chlikData: editData.listingTime,
        imgArray: res.houImageVO,
        inputFloorNum: editData.floorHeight,
        buyPrice: (editData.buyPrice)/10000,
        valueLength: editData.notes ? editData.notes.length : '0',
        textInfo: editData.notes,
        'moreValue.serviceLife': editData.houYears,
        'moreValue.notTheOnly': editData.unique,
        'moreValue.floor': editData.buildNumNew,
        'moreValue.decoration': editData.decorateType,
        'moreValue.orientation': editData.direction,
        'moreValue.feature': editData.lightSpot,
        delId: editData.delId
      })
      wx.hideLoading()
    })
  },
  // 修改标题
  titleEditButton() {
    app.globalData.inputTextValuePage = this.data.houseTitle
    p.navigateTo({
      url: `/pages/addHouse/inputTextValue/inputTextValue?placeholder=请输入房源标题&maxCount=20`
    })
    this.data.backFromInputTextValuePageCb = () => {
      this.setData({
        houseTitle: app.globalData.inputTextValuePage
      })
      app.globalData.inputTextValuePage = ""
    }
  },
  // 售价、租金
  inputTotalPrices(e) {
    this.setData({
      totalPrices: e.detail.value,
    });
  },
  // 打开户型组件
  onClickHouseType() {
    this.setData({
      isShowHouseTypeSheet: true,
    })
  },
  // 关闭户型组件
  onHouseTypeClose() {
    this.setData({
      isShowHouseTypeSheet: false,
    })
  },
  // 修改户型
  onHouseTypeChange(e) {
    const {
      hall,
      room,
      toilet
    } = e.detail.form || {}
    this.setData({
      'model.hall': hall,
      'model.room': room,
      'model.toilet': toilet,
    })
  },
  // 修改面积
  inputBuildSize(e) {
    this.setData({
      buildSize: e.detail.value,
    });
  },
  // 修改挂牌时间
  bindDateChange(e) {
    this.setData({
      chlikData: e.detail.value
    })
  },
  //上传图片
  handleSelectImg() {
    let num = this.data.imgMax - this.data.imgArray.length;
    if (num == 0) return wx.showToast({
      icon: "none",
      title: "已达最大图片数！"
    });
    wx.chooseImage({
      sourceType: ["album"], // 从相册选择
      count: num,
      success: (res) => {
        let filePathArr = res.tempFilePaths;
        let promiseList = filePathArr.map((item) => {
          return new Promise((resolve, reject) => {
            util.uploadFiles(item, (res) => {
              try {
                var id = JSON.parse(res.data)[0].id;
                var obj = {
                  fileId: id,
                  url: item,
                };
                resolve(obj);
                
              } catch (error) {
                reject()
              }
            });
          });
        });
        Promise.all(promiseList).then((list) => {
          let arr = this.data.imgArray.concat(list);

          arr.length = Math.min(arr.length, this.data.imgMax);
          this.setData({
            imgArray: arr,
          });
        });
      },
    });
  },
  // 图片删除
  handleCancel(e) {
    let id = e.currentTarget.dataset.fileid;
    this.setData({
      imgArray: this.data.imgArray.filter((v) => v.fileId != id),
    });
  },
  // 楼层
  inputFloorNum(e) {
    let inputFloorNum = e.detail.value
    this.setData({
      inputFloorNum
    })
  },
  //买进价
  inputBuyPrice(e) {
    this.data.buyPrice = e.detail.value
  },
  // 房源备注说明
  dynamicValue(e) {
    let value = e.detail.value
    this.setData({
      valueLength: value.length,
      textInfo: value
    })
  },

  //小按钮的点击事件
  onInfoTypeChange(e) {
    let id = e.currentTarget.dataset.id
    let data = e.detail
    let path = `moreValue.${id}`
    this.setData({
      [path]: data
    })
  },

  // 编辑房源
  handleSaveSALES() {
    if (!this.data.isPublishAble) return;
    let {
      totalPrices,
      totalPricesSave,
      buildSizeSave,
      buildSize,
      hdResblockId,
      delegationType,
    } = this.data
    let inputData = {
      buildSize,
      totalPrices,
      hdResblockId
    }
    // 如修改信息为面积、价格中任一项，点击保存即进入校验结果弹窗，
    // 点击【保存发布】， 即同步更新该房源信息，同时页面返回更新后的房源详情页；
    if (totalPricesSave !== Number(totalPrices) || buildSizeSave !== Number(buildSize) && delegationType=='SALES') {
      return new Promise((resolve, reject) => {
        api.authenticityCheck(inputData, (res) => {
          if (res && res.data && res.data.isSuccess) {
            let results = res.data.content
            results.isEditPage = true
            this.setData({
              authenticityId: results.authenticityCheckId
            })
            if (results.buildSizeCheck == 0 && results.totalPricesCheck == 0) { //面积和价钱都没有匹配结果
              this.editInfoApi()
            } else {
              this.setData({
                dataDetectionInfo: results, //检测弹窗需要的数据
                isShowDataDetection: true
              })
            }
            resolve();
          }
        })
      })

    } else {
      this.editInfoApi()
    }

  },

  // 树懒大数据检测
  handleHide(e) {
    let visible = e.detail.visible
    this.setData({
      isShowDataDetection: visible
    })
  },
  backButtom() {
    this.setData({
      isShowDataDetection: false
    })
  },
  confirmButtom() {
    this.editInfoApi()
  },

  // 修改接口
  editInfoApi() {
    return new Promise((resolve, reject) => {
      let that = this
      let editInfo = {
        id: that.data.id,
        title: that.data.houseTitle,
        totalPrices: that.data.delegationType == "SALES" ? that.data.totalPrices : "",
        rent: that.data.delegationType == "RENT" ? that.data.totalPrices : "",
        room: typeof (that.data.model.room) === 'object' ? that.data.model.room.input : that.data.model.room,
        hall: typeof (that.data.model.hall) === 'object' ? that.data.model.hall.input : that.data.model.hall,
        toilet: typeof (that.data.model.toilet) === 'object' ? that.data.model.toilet.input : that.data.model.toilet,
        buildSize: that.data.buildSize,
        listingTime: that.data.chlikData || '',
        houYears: that.data.moreValue.serviceLife,
        unique: that.data.moreValue.notTheOnly,
        buildNumNew: that.data.moreValue.floor,
        floorHeight: that.data.inputFloorNum,
        decorateType: that.data.moreValue.decoration,
        direction: that.data.moreValue.orientation,
        lightspot: that.data.moreValue.feature || [],
        buyPrice: that.data.buyPrice? (that.data.buyPrice)*10000: '',
        notes: that.data.textInfo || '',
        authenticityId: that.data.authenticityId
      }
      this.updateImage()
      api.houseAndCommissionUpdate(editInfo, (res) => {
        if (res && res.data && res.data.isSuccess) {
          transferData.setData("isRefreshCooperation", true);
          wx.navigateBack({
            delta: 1,
          })
          resolve();
        } else {
          wx.showToast({
            title: res.data.errorMessage,
            icon: 'none',
            duration: 1000
          })
        }
      });
    });
  },

  // 图片修改
  updateImage() {
    return new Promise((resolve, reject) => {
      let imgArray = this.data.imgArray
      let delId = this.data.delId
      for (let i in imgArray) {
        imgArray[i].cover = i
        imgArray[i].houDelId = delId
        imgArray[i].type = 'pic'
      }
      api.updateImage({
        houImgList: imgArray
      }, (res) => {})
    })
  }
})